package io.zztec.config;

import io.zztec.plugin.PagePlugin;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.util.Properties;

/**
 * Created by zztec on 2016-01-04.
 */
@MapperScan(basePackages = "io.zztec.mapper")
@Configuration
public class MyBatisConfig {

    @Autowired
    private DruidConfig druidConfig;

    public MyBatisConfig(){
        System.out.println("init MyBatisConfig");
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(druidConfig.mysqlDataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("io.zztec.domain");


        //设置 properties
        Properties properties = new Properties();
        properties.setProperty("dialect","mssql");
        properties.setProperty("pageSqlId",".*query.*");

        PagePlugin pagePlugin = new PagePlugin();
        pagePlugin.setProperties(properties);

        //设置自定义插件
        Interceptor[] interceptors = new Interceptor[1];
        interceptors[0] = pagePlugin;
        sqlSessionFactoryBean.setPlugins(interceptors);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(druidConfig.mysqlDataSource());
    }
}
